/*
  彩灯模块
*/
#define BLYNK_PRINT Serial
#define RGBPin 15
#define NUMPIXELS 150
#include <Wire.h>
#include <WiFiManager.h>
#include <SimpleTimer.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>
SimpleTimer timer;
char sound_auth[] = "FlVPYSmNpCzJRBN3mzwQf9MHbkRBcgRr";
float Noise;
int YELLOW_TIME, RED_TIME,hue;
Adafruit_NeoPixel rgb_display = Adafruit_NeoPixel(NUMPIXELS, RGBPin, NEO_GRB + NEO_KHZ800);

BLYNK_WRITE(V0) {
  Noise = param.asFloat();
  Serial.println(Noise);
  if (Noise > 80)
    RED_TIME = 6;
  else if (Noise > 70)
    YELLOW_TIME = 6;
}
void rainbow() {
  for (int i = 0; i <= NUMPIXELS; i ++ ) {
    for (int j = 0; j <= NUMPIXELS; j++ ) {
      hue = (i + j) % (NUMPIXELS+1) * (65536/NUMPIXELS);//计算每一盏灯的颜色值
      rgb_display.setPixelColor(j , rgb_display.ColorHSV(hue, 255, 255));
    }
    rgb_display.show();
    delay(5);
  }
}
void DisplayTime() {
  if (RED_TIME)
  {
    for (int j = 0; j <= NUMPIXELS; j ++)
      rgb_display.setPixelColor(j, 0xff0000);//全部亮红色
    rgb_display.show();
    RED_TIME--;
  }
  else if (YELLOW_TIME)
  {
    for (int j = 0; j <= NUMPIXELS; j ++)
      rgb_display.setPixelColor(j, 0xffff00);//全部亮黄色
    rgb_display.show();
    YELLOW_TIME--;
  }
  else
    rainbow();
}

void setup() {
  Serial.begin(115200);
  WiFiManager wifiManager;
  rgb_display.begin();
  if (!wifiManager.autoConnect("RGB")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  Blynk.config(sound_auth, "blynk.mixly.org", 8080);
  timer.setInterval(1550L, DisplayTime);
}
void loop() {
  timer.run();
  Blynk.run();
}
